#include "databasepool.h"
#include <QDebug>
#include <QSqlError>
#include <QThread>
#include <QSqlQuery>

// 初始化连接计数器
int DatabasePool::connectionCounter = 0;
const int DatabasePool::MAX_CONNECTIONS = 15; // 最大连接数量

// 获取单例实例
DatabasePool& DatabasePool::instance() {
    static DatabasePool pool;
    return pool;
}

// 获取数据库连接
// DatabasePool::getConnection
QSqlDatabase DatabasePool::getConnection() {
    QMutexLocker locker(&m_mutex);
    while (m_connections.isEmpty() && connectionCounter >= MAX_CONNECTIONS) {
        m_connectionAvailable.wait(&m_mutex);
    }

    if (!m_connections.isEmpty()) {
        // 若队列中有可用连接，直接取出
        QSqlDatabase db = m_connections.dequeue();
        if (db.isOpen()) {
            db.exec("PRAGMA foreign_keys = ON;"); // 确保启用外键
            return db;
        } else {
            // 若连接已关闭，重新打开
            if (db.open()) {
                db.exec("PRAGMA foreign_keys = ON;"); // 确保启用外键
                return db;
            } else {
                qDebug() << "Failed to reopen database: " << db.lastError().text();
            }
        }
    }

    // 创建新连接
    QString connectionName = QString("snail_iot_connection_%1").arg(connectionCounter++);
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
    db.setDatabaseName("snail_iot.db");
    if (db.open()) {
        db.exec("PRAGMA foreign_keys = ON;"); // 确保启用外键
        m_connections.enqueue(db);
    } else {
        qDebug() << "Failed to open database: " << db.lastError().text();
    }
    return db;
}

// 释放数据库连接
void DatabasePool::releaseConnection(QSqlDatabase conn) {
    QMutexLocker locker(&m_mutex);
    if (conn.isOpen()) {
        // 若连接仍然有效，将其放回队列
        m_connections.enqueue(conn);
    } else {
        // 若连接已关闭，重新打开或者创建新连接
        if (conn.open()) {
            m_connections.enqueue(conn);
        } else {
            qDebug() << "Failed to reopen database: " << conn.lastError().text();
            QString connectionName = QString("snail_iot_connection_%1").arg(connectionCounter++);
            QSqlDatabase newDb = QSqlDatabase::addDatabase("QSQLITE", connectionName);
            newDb.setDatabaseName("snail_iot.db");
            if (newDb.open()) {
                m_connections.enqueue(newDb);
            } else {
                qDebug() << "Failed to create new database connection: " << newDb.lastError().text();
            }
        }
    }
    m_connectionAvailable.wakeOne();
}

// 构造函数，初始化连接池
DatabasePool::DatabasePool(QObject* parent) : QObject(parent) {
    for (int i = 0; i < MAX_CONNECTIONS; ++i) {
        QString connectionName = QString("snail_iot_connection_%1").arg(connectionCounter++);
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
        db.setDatabaseName("snail_iot.db");
        if (db.open()) {
            // 若连接打开成功，将其加入队列
            m_connections.enqueue(db);
        } else {
            qDebug() << "Failed to open database during initialization: " << db.lastError().text();
        }
    }
}

// 析构函数，关闭并移除所有连接
DatabasePool::~DatabasePool() {
    while (!m_connections.isEmpty()) {
        QSqlDatabase db = m_connections.dequeue();
        db.close();
        QSqlDatabase::removeDatabase(db.connectionName());
    }
}
